package com.prestamomo.vil.ppa.pmvilpage;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.LinearLayoutCompat;

import com.prestamomo.vil.ppa.R;
import com.prestamomo.vil.ppa.pmvilapi.PmvilHttpRequest;
import com.prestamomo.vil.ppa.pmvilapi.PmvilLoginBean;
import com.prestamomo.vil.ppa.pmvilapi.PmvilMsgCode;
import com.prestamomo.vil.ppa.pmvilmedium.pmviluse.PmvilPermissMd;
import com.prestamomo.vil.ppa.pmvilmedium.pmviluse.PmvilSpMd;
import com.prestamomo.vil.ppa.pmvilmedium.pmviluse.PmvilTosMd;
import com.prestamomo.vil.ppa.pmvilnet.PmvilAjustinfse;
import com.prestamomo.vil.ppa.pmvilnet.PmvilRetrofitHelper;
import com.prestamomo.vil.ppa.pmvilnet.pmvillistener.PmvilCallBack;
import com.prestamomo.vil.ppa.pmvilpage.pmrot.PmvilAtyRoot;

import java.util.HashMap;
import java.util.Map;

public class PmvilLoginVy extends PmvilAtyRoot {

    private EditText loginPmPhenEt;
    private EditText loginPmCodeEt;
    private LinearLayoutCompat loginPmLlCode;
    private RelativeLayout loginPmRlDjsOrReast;
    private TextView loginPmTvDjs;
    private ImageView loginPmIvResat;
    private Button loginPmBtnCode;
    private Button loginPmBtnLogin;
    private ImageView loginPmIvXy;
    private TextView loginPmTvXy;

    private View loginPmViewzg;

    private boolean isPmLoginCheck = false;
    private CountDownTimer pmvilCountDownTimer;

    @Override
    protected int getPmvilLayoutId() {
        return R.layout.login_pmvil_ly;
    }

    @Override
    protected void showPmvilUi() {
        loginPmViewzg = findViewById(R.id.login_pmvil_view_zg);
        loginPmPhenEt = findViewById(R.id.login_pmvil_et_phone);
        loginPmCodeEt = findViewById(R.id.login_pmvil_et_code);
        loginPmLlCode = findViewById(R.id.login_pmvil_ll_code);
        loginPmRlDjsOrReast = findViewById(R.id.login_pmvil_rl_djsorreaset);
        loginPmTvDjs = findViewById(R.id.login_pmvil_tv_djs);
        loginPmIvResat = findViewById(R.id.login_pmvil_iv_resat);
        loginPmBtnCode = findViewById(R.id.login_pmvil_btn_code);
        loginPmBtnLogin = findViewById(R.id.login_pmvil_btn_login);
        loginPmIvXy = findViewById(R.id.login_pmvil_iv_xy);
        loginPmTvXy = findViewById(R.id.login_pmvil_tv_xy);
        loginPmTvXy.setText(Html.fromHtml("請閱讀我們的 <font color ='#FF7B31'><u>隱私權政策</u></font>"));

        loginPmPhenEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (loginPmBtnCode.getVisibility() == View.VISIBLE) {
                        loginPmBtnCode.setEnabled(true);
                        loginPmBtnCode.setBackgroundResource(R.drawable.sp_pm_tvbg_hs);
                    } else {
                        loginPmBtnCode.setEnabled(false);
                        loginPmBtnCode.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                    }
                    if (loginPmBtnLogin.getVisibility() == View.VISIBLE) {
                        if (loginPmCodeEt.getText().toString().length() > 0) {
                            loginPmBtnLogin.setEnabled(true);
                            loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_tvbg_hs);
                        } else {
                            loginPmBtnLogin.setEnabled(false);
                            loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                        }
                    }
                } else {
                    if (loginPmBtnCode.getVisibility() == View.VISIBLE) {
                        loginPmBtnCode.setEnabled(false);
                        loginPmBtnCode.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                    }
                    if (loginPmBtnLogin.getVisibility() == View.VISIBLE) {
                        loginPmBtnLogin.setEnabled(false);
                        loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                    }
                }
            }
        });
        loginPmCodeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (loginPmBtnLogin.getVisibility() == View.VISIBLE) {
                        if (loginPmPhenEt.getText().toString().length() > 0) {
                            loginPmBtnLogin.setEnabled(true);
                            loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_tvbg_hs);
                        } else {
                            loginPmBtnLogin.setEnabled(false);
                            loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                        }
                    } else {
                        loginPmBtnLogin.setEnabled(false);
                        loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                    }
                } else {
                    loginPmBtnLogin.setEnabled(false);
                    loginPmBtnLogin.setBackgroundResource(R.drawable.sp_pm_btnbg_hs);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean b = PmvilPermissMd.checkPmvilAllPermiss(this);
        if (!b) {
            loginPmViewzg.setVisibility(View.VISIBLE);
        } else {
            if (PmvilPermissMd.phonePmvpXMi(this)) {
                loginPmViewzg.setVisibility(View.GONE);
            } else {
                loginPmViewzg.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void clickePmvil() {
        loginPmViewzg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(pmvilAy, PmvilPermissVy.class));
            }
        });
        loginPmBtnCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendAdjPmvilEvent(PmvilAjustinfse.pmvildddwewesew);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvildddwewesew_0);
                pmvilLoginGetCode(true, loginPmPhenEt.getText().toString(), "text");
            }
        });

        loginPmBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> pmvilLogiMap = new HashMap<>();
                if (isPmLoginCheck) {
                    sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lyuthhtrre_bt);
                    sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lyuthhtrre_bt_0);
                    pmvilLogiMap.put("pmvillongils", "text");
                    postPmvilLogin(loginPmPhenEt.getText().toString(),
                            loginPmCodeEt.getText().toString(), "text");
                } else {
                    pmvilLogiMap.put("pmvillongils", "none");
                    showPmvilXyDlg();
                }
                if (pmvilLogiMap.size() != 0) {
                    pmvilLogiMap.clear();
                }

            }
        });

        loginPmRlDjsOrReast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendAdjPmvilEvent(PmvilAjustinfse.pmvildddwewesew);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvildddwewesew_0);
                pmvilLoginGetCode(false, loginPmPhenEt.getText().toString(), "text");
            }
        });

        loginPmIvXy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPmLoginCheck = !isPmLoginCheck;
                loginPmIvXy.setImageResource(isPmLoginCheck ? R.mipmap.login_pm_icon3 : R.mipmap.login_pm_icon2);
            }
        });

        loginPmTvXy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToPmvilXy();
            }
        });
    }

    @Override
    protected void loadPmvilData() {
        getPmvilLjiswt("kiwlw", "kiwoss");
    }

    private void pmvilLoginGetCode(boolean pmvilFirst, String pmvilLoginMobel, String pmvilLoginCodeType) {
        showPmvilLoading();
        PmvilHttpRequest.getCodePmvilMsg(this, pmvilLoginMobel, pmvilLoginCodeType, new PmvilCallBack<PmvilMsgCode>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, PmvilMsgCode pmvilContent) {
                hindPmvilLoading();
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_dddwweqw_t);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_dddwweqw_t_0);
                getPmvilCodeFirst(pmvilFirst);
                resatPmvilCode(pmvilContent.getPmvilPMexpiry() * 1000L);
                if (pmvilContent.getPmvilPMstatus().equals("Y")) {
                    initPmvilCodePop(loginPmCodeEt, pmvilContent.getPmvilPMtransId());
                }
            }

            @Override
            public void onPmvilLogOn(String pmvilMod, PmvilMsgCode pmvilCtent) {
                outpmvilLongin();
            }

            @Override
            public void onPmvilOther(String pmvilMhod, PmvilMsgCode pmvilCnt, String pmvilCode, String pmvilMsg) {
                tostPmvilErrMsg(pmvilMsg);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_jkdiwdww_e);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_jkdiwdww_e_0);
                if (pmvilCode.equals("455")) {
                    loginPmTvDjs.setVisibility(View.GONE);
                    loginPmIvResat.setVisibility(View.VISIBLE);
                    loginPmRlDjsOrReast.setEnabled(true);
                    loginPmRlDjsOrReast.setBackgroundResource(R.drawable.sp_pm_rlbg_hs1);
                    getPmvilCodeFirst(pmvilFirst);
                }
            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {
                tostPmvilErrMsg(pmvilError);
            }
        });
    }

    private void getPmvilLjiswt(String pmvilTIlw, String pmvilPdkw) {
        PmvilHttpRequest.getPmvilLjiswt(this, pmvilTIlw, pmvilPdkw, new PmvilCallBack<String>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, String pmvilContent) {

            }

            @Override
            public void onPmvilLogOn(String pmvilMod, String pmvilCtent) {

            }

            @Override
            public void onPmvilOther(String pmvilMhod, String pmvilCnt, String pmvilCode, String pmvilMsg) {

            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {

            }
        });
    }

    private void resatPmvilCode(long pmvilTimeAll) {
        loginPmTvDjs.setVisibility(View.VISIBLE);
        loginPmIvResat.setVisibility(View.GONE);
        loginPmRlDjsOrReast.setBackgroundResource(R.drawable.sp_pm_rlbg_hs);
        pmvilCountDownTimer = new CountDownTimer(pmvilTimeAll, 1000L) {
            @Override
            public void onTick(long millisUntilFinished) {
                loginPmTvDjs.setText(millisUntilFinished / 1000L + "S");
                loginPmRlDjsOrReast.setEnabled(false);
            }

            @Override
            public void onFinish() {
                if (pmvilCountDownTimer != null) {
                    pmvilCountDownTimer.cancel();
                    pmvilCountDownTimer = null;
                }
                loginPmTvDjs.setVisibility(View.GONE);
                loginPmIvResat.setVisibility(View.VISIBLE);
                loginPmRlDjsOrReast.setEnabled(true);
                loginPmRlDjsOrReast.setBackgroundResource(R.drawable.sp_pm_rlbg_hs1);
            }
        };
        pmvilCountDownTimer.start();
    }

    private void getPmvilCodeFirst(boolean pmvilFirst) {
        if (pmvilFirst) {
            loginPmBtnCode.setVisibility(View.GONE);
            loginPmLlCode.setVisibility(View.VISIBLE);
            loginPmBtnLogin.setVisibility(View.VISIBLE);
        }
    }


    private void initPmvilCodePop(View v, String pmvilCode) {
        View pmvilCodePop = LayoutInflater.from(this).inflate(R.layout.code_pmvil_pop, null, false);
        final PopupWindow codePmvilPopWindow = new PopupWindow(pmvilCodePop, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        codePmvilPopWindow.setTouchable(true);
        codePmvilPopWindow.showAsDropDown(v);
        TextView pmvilTvCode = pmvilCodePop.findViewById(R.id.code_pmvil_pop_tv_code);
        pmvilTvCode.setText(pmvilCode);
        TextView pmvilCodeOk = pmvilCodePop.findViewById(R.id.code_pmvil_pop_tv_ok);
        pmvilCodeOk.setOnClickListener(v1 -> codePmvilPopWindow.dismiss());
        codePmvilPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                loginPmCodeEt.setText(pmvilCode);
            }
        });
    }


    private void postPmvilLogin(String pmvilPhone, String pmvilCode, String pmvilType) {
        showPmvilLoading();
        PmvilHttpRequest.postPmvilLogin(this, pmvilPhone, pmvilCode, pmvilType, new PmvilCallBack<PmvilLoginBean>() {
            @Override
            public void onPmvilSucc(String pmvilMethod, PmvilLoginBean pmvilContent) {
                hindPmvilLoading();
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_ktyhgfdgre_t);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_ktyhgfdgre_t_0);
                PmvilSpMd.putPmvaParam(pmvilAy, "pmvil_userId_pm", pmvilContent.getPmvilPMuserId());
                PmvilSpMd.putPmvaParam(pmvilAy, "pmvil_uuId_pm", pmvilContent.getPmvilPMuuId());
                PmvilSpMd.putPmvaParam(pmvilAy, "pmvil_times_sms", pmvilContent.getPmvilPMtimeStamp());
                PmvilSpMd.getPmvaParam(pmvilAy,"onTest",pmvilContent.isPmvilPMonTest());
                startActivity(new Intent(pmvilAy, PmvilOwnerVy.class));
                finish();
            }

            @Override
            public void onPmvilLogOn(String pmvilMod, PmvilLoginBean pmvilCtent) {
                outpmvilLongin();
            }

            @Override
            public void onPmvilOther(String pmvilMhod, PmvilLoginBean pmvilCnt, String pmvilCode, String pmvilMsg) {
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lytgsgerdfgr_e);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lytgsgerdfgr_e_0);
                tostPmvilErrMsg(pmvilMsg);
            }

            @Override
            public void onPmvilFailure(String pmvilMod, String pmvilError) {
                tostPmvilErrMsg(pmvilError);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lytgsgerdfgr_e);
                sendAdjPmvilEvent(PmvilAjustinfse.pmvil_lytgsgerdfgr_e_0);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pmvilCountDownTimer != null) {
            pmvilCountDownTimer = null;
        }
    }

    private void showPmvilXyDlg() {
        AlertDialog.Builder xyPmvilBlder = new AlertDialog.Builder(this, R.style.pm_dlg_stl);
        View pmvilXyView = this.getLayoutInflater().inflate(R.layout.xy_pmvil_dlg, null);
        ImageView pmvilIvClost = pmvilXyView.findViewById(R.id.xy_pmvildlg_close);
        LinearLayout pmvilLlTzxy = pmvilXyView.findViewById(R.id.xy_pmvildlg_tzxy);
        TextView pmvilTvBh = pmvilXyView.findViewById(R.id.xy_pmvildlg_tv_bh);
        TextView pmvilTvTy = pmvilXyView.findViewById(R.id.xy_pmvildlg_tv_ty);
        xyPmvilBlder.setView(pmvilXyView);
        xyPmvilBlder.setCancelable(false);
        AlertDialog pmvilXyDlg = xyPmvilBlder.create();
        pmvilXyDlg.show();
        initPmvilXydg(pmvilIvClost, pmvilLlTzxy, pmvilTvBh, pmvilTvTy, pmvilXyDlg);
    }

    private void initPmvilXydg(ImageView pmvilIvClost, LinearLayout pmvilLlTzxy, TextView pmvilTvBh, TextView pmvilTvTy, AlertDialog pmvilXyDlg) {
        pmvilIvClost.setOnClickListener(v -> pmvilXyDlg.dismiss());
        pmvilTvBh.setOnClickListener(v -> pmvilXyDlg.dismiss());
        pmvilTvTy.setOnClickListener(v -> {
            pmvilXyDlg.dismiss();
            isPmLoginCheck = true;
            loginPmIvXy.setImageResource(R.mipmap.login_pm_icon3);
        });
        pmvilLlTzxy.setOnClickListener(v -> {
            pmvilXyDlg.dismiss();
            goToPmvilXy();
        });
    }

    private void goToPmvilXy() {
        goToPmvilXyAty("隱私權政策", PmvilRetrofitHelper.pmvilWebXYUrl);
    }

    private long pmvilBackTime = 0;

    @Override
    public void onBackPressed() {
        long pmvilNowTime = System.currentTimeMillis();
        if (pmvilNowTime - pmvilBackTime > 2000) {
            PmvilTosMd.showPmvaMsg("再次按返回鍵退出應用程式");
            pmvilBackTime = pmvilNowTime;
        } else {
            finish();
        }
    }
}
